package com.birth.memo.ui;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.OnItemSelectedListener;

import com.birth.memo.R;
import com.birth.memo.util.Constants;

public class ViewSmsList extends Activity {
	
	private static final int MENU_SEND_SMS = 1;
	
	private ListView smsList;
	
	private long curId = 1;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);		
		this.setContentView(R.layout.view_sms_list);
		
		smsList = (ListView)this.findViewById(R.id.smsList);
		
		
        Cursor c = getContentResolver().query(Constants.URI_SMS, null, null, null, null);
        startManagingCursor(c);

        ListAdapter adapter = new SimpleCursorAdapter(this, 
                R.layout.list_item, 
                c, 
                new String[] {"sms"} ,
                new int[] {R.id.txt_sms}); 
        smsList.setAdapter(adapter);
        smsList.setOnItemSelectedListener(new OnItemSelectedListener(){
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int position, long id) {				
				curId = id;
			}
			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				
			}
        	
        });
        smsList.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {  
        	  
            public void onCreateContextMenu(ContextMenu conMenu, View view , ContextMenuInfo info) {  
                 conMenu.setHeaderTitle("菜单");  
                 conMenu.add(0, MENU_SEND_SMS, 0, "作为短信发送");                   
               
            }  
       }); 
		
	}
	
	public boolean onContextItemSelected (MenuItem item) {
    	super.onContextItemSelected(item);    	
    	switch(item.getItemId()){
    	case MENU_SEND_SMS:
    		Cursor c = getContentResolver().query(Constants.URI_SMS, null,"_id =?", new String[]{String.valueOf(curId)}, null);
    		startManagingCursor(c);
    		String sms = null;
    		if(c.moveToFirst()){
    			sms = c.getString(c.getColumnIndex("sms"));
    			prepareSms(sms);
    		}
    		break;    	
    	}
    	
    	return false;
    }
	
	 private void prepareSms(String content){
	    	Intent it = new Intent(Intent.ACTION_VIEW);    
	    	it.putExtra("sms_body", content);    
	    	it.setType("vnd.android-dir/mms-sms");    
	    	startActivity(it);  
	    }

}
